#pragma once
#include <queue>
#include <pthread.h>
#include "LockGuard.hpp"
const int gcapacity = 8;

template <class T>
class BlockQueue
{
public:
    BlockQueue(int capacity = gcapacity)
        : _capacity(capacity)
    {
        _consumer_water_line = capacity / 3 * 2;
        _productor_water_line = capacity / 3 * 1;
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
    }

    void Push(const T &in)
    {
        LockGuard lockguard(&_mutex);
        while (IsFull()) // 这样写，健壮性更好
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        _q.push(in);
        if (_q.size() > _productor_water_line) //大于补货线，就通知生产者来消费
            pthread_cond_signal(&_c_cond);
    }

    void Pop(T *out)
    {
        LockGuard lockguard(&_mutex);
        while (IsEmpty())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        *out = _q.front();
        _q.pop();
        if (_q.size() < _consumer_water_line) //小于消费线，就来供货
            pthread_cond_signal(&_p_cond);
    }

    bool IsFull()
    {
        return _q.size() == _capacity;
    }

    bool IsEmpty()
    {
        return _q.size() == 0;
    }
    ~BlockQueue()
    {
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
        pthread_mutex_destroy(&_mutex);
    }
    std::string debug(){
        std::string ret="q.size():";
        ret+=std::to_string(_q.size());
        ret+=",_consumer_water_line:";
        ret+=std::to_string(_consumer_water_line);
        ret+=",_productor_water_line:";
        ret+=std::to_string(_productor_water_line);
        return ret;
    }
private:
    std::queue<T> _q;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _c_cond;    // 给消费者用的
    pthread_cond_t _p_cond;    // 给生产者用的
    int _consumer_water_line;  // 低于这个数，通知生产者生产
    int _productor_water_line; // 高于这个数，通知消费者来消费
};